#####################
# Sleep Project - Pedro Bessone, Gautam Rao, Heather Schofield, Frank Schilbach, and Mattie Toma
# Purpose: Replicates Figure 9 from the Appendix (Relationship Between Increases in 24-Hour Sleep and Treatment Effects on Overall Index)
# Last edited: 07 May 2021
#####################

rm(list = ls())

#install.packages("ggplot2")
require(ggplot2)
#install.packages("ggrepel")
require(ggrepel)

# Graph theme
mytheme = theme_bw() +
  theme(panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank(),
        panel.grid.minor.y = element_blank(),
        panel.border = element_blank(),
        axis.line = element_line(color = "black"),
        text =  element_text(size = 12),
        axis.text = element_text(color = "black"), 
        legend.text = element_text(face = "bold"),
        legend.position = "bottom",
        plot.title = element_text(hjust = 0, size = 11, face = "bold"))

require(tidyverse)

# Data set with treatment fxs on total sleep and overall ind. for each treat. combination
df = tibble(
  treat = c("Nap", "Encouragement", "Incentives", "Nap + Encouragement", "Nap + Incentives"),
  total_sleep = c(5.4, 19.8, 29.4, 25.2, 42), #first stage is made up, substitute for real one
  overall_ind = c(11,0,-5,13, 9)/100,
  overall_ind_se = c(0.07,0.07,0.07,0.07, 0.06)
) %>% 
  arrange(total_sleep) %>% 
  mutate(treat = factor(treat, 
                        levels = treat))

# Graph style 1
breaks = df$total_sleep
breaks.lab.mins = paste0("\n", paste0(breaks, " mins")) 
breaks.lab = paste0(df$treat, breaks.lab.mins)

df %>% 
  ggplot(aes(x = total_sleep, y = overall_ind)) +
  mytheme +
  geom_hline(yintercept = 0, lty = 2, color = "tomato") +
  geom_point(size = 3) +
  scale_y_continuous() +
  labs(x = "Total sleep (minutes)", 
       y = "Overall index (SDs)") +
  scale_x_continuous(breaks = breaks, labels = breaks.lab)

# Graph style 2
breaks = sort(c(df$total_sleep, seq(10,40,10)))

breaks.lab = as.character(breaks)
breaks.lab[breaks %in% df$total_sleep] = levels(df$treat)

figure <- df %>% 
  ggplot(aes(x = total_sleep, y = overall_ind)) +
  geom_errorbar(aes(ymin=overall_ind-(1.96*overall_ind_se), ymax=overall_ind+(1.96*overall_ind_se)), colour="light blue",  width=.6) +
  mytheme + 
  geom_hline(yintercept = 0, lty = 2, color = "tomato") +
  geom_point(size = 3) +
  labs(x = "Increase in 24-hour sleep (mins)", 
       y = "Treatment effect on overall index (SD)") +
  scale_x_continuous(breaks = seq(5,45, 5), limits = c(5,45)) +
  geom_text(aes(label = treat), nudge_y = +0.02, size=6) #-> g2; g2 

figure + theme(text = element_text(size = 18)) -> g2; g2 


ggsave("Output/Appendix/Figures/FigureA9_scatter_sleep_vs_overall_if.pdf", g2, height = 7)
ggsave("Output/Appendix/Figures/FigureA9_scatter_sleep_vs_overall_if.eps", g2, height = 7)

